package com.sugon.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinAdd {

	public static void main(String[] args) {
		System.out.println("cpu核数"+Runtime.getRuntime().availableProcessors());
		
		ForkJoinPool pool = new ForkJoinPool();
		AddTask main = new AddTask(1 , 100000);
		Long result = pool.invoke(main);
		System.out.println("结果"+result);


	}
}

class AddTask extends RecursiveTask<Long>{
	int start;
	int end;
	static final int THRESHOLD = 1000;
	public AddTask(int start, int end) {
		super();
		this.start = start;
		this.end = end;
	}
	@Override
	public Long compute() {
		//如果start和end之间差距低于THRESHOLD 直接计算
		if (end - start <= THRESHOLD){
			long result = 0 ; 
			for(int i = start ; i<= end ; i++){
				result += i;
			}
			return result;
		}
		//否则 就要把任务分割为两个子任务
		else{
			int middle = (start+end)/2;
			AddTask task1 = new AddTask(start , middle);
			AddTask task2 = new AddTask(middle+1 , end);
			invokeAll(task1 , task2);
			long r1 = task1.join();
			long r2 = task2.join();
			return r1+r2;
		}
	}
	
	
}